package me.yobol.greentable.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.yobol.greentable.bean.IngredientBean;
import me.yobol.greentable.service.IngredientService;

/**
 * @author Yobol
 * 
 */
public class GetIngredientListServlet extends HttpServlet {

	private static final long serialVersionUID = -2631970284671908289L;
	public GetIngredientListServlet() {
		super();
	}

	public void init() throws ServletException {
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int traderId = (request.getSession().getAttribute("uId") == null) ? -1
				: (Integer) request.getSession().getAttribute("uId");
		int flag = (request.getParameter("flag") == null) ? -1 : Integer
				.parseInt(request.getParameter("flag"));

		String redirect = null;
		
		if (flag == 0) {
			List<IngredientBean> allIngredient = IngredientService
					.getAllIngredient();
			request.getSession().setAttribute("ingredient_list", allIngredient);

			redirect = "/pages/ingredient/ingredient_list.jsp";
		} else if(flag == 1 && traderId > 0) {
			List<IngredientBean> igByTrader = IngredientService
					.getIngredientByTraderId(traderId);
			request.getSession().setAttribute("ingredient_list", igByTrader);
			redirect = "/pages/ingredient/ingredient_list.jsp?flag=" + flag;
		}

		response.sendRedirect(request.getContextPath() + redirect);
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
